package com.itlong.cloud.controller.finance;

import com.itlong.cloud.POJO.DTO.operate.OperateAmountChangeGetPageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateAmountChangeGetPageVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.paymenthub.IOperateAmountChangeClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营-资金变动明细控制器
 * </desc>
 *
 * @createDate 2018/09/21
 */
@RestController
@RequestMapping("/finance/amountChangeManage")
@RefreshScope
public class OperateAmountChangeController extends BaseController {

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;

    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;

    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;

    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;

    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    @Autowired
    private IOperateAmountChangeClient iOperateAmountChangeClient;

    /**
     * <desc>
     *      分页获取资金变动明细
     * </desc>
     *
     * @param operateAmountChangeGetPageDTO 运营-资金变动明细列表查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/09/21
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("getPage")
    public Object getPage(OperateAmountChangeGetPageDTO operateAmountChangeGetPageDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateAmountChangeGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateAmountChangeGetPageDTO.class,request);
            if (operateAmountChangeGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateAmountChangeGetPageDTO.getAmountType(), 1, 3)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(operateAmountChangeGetPageDTO.getTime())) {
                operateAmountChangeGetPageDTO.setTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            }
            Page<OperateAmountChangeGetPageVO> page = iOperateAmountChangeClient.getPage(operateAmountChangeGetPageDTO);
            if (page.getRows() == null || page.getRows().isEmpty()) {
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),(Object) new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【运营-资金变动明细getPage】分页获取资金变动明细信息失败",e);
        }
    }

    /**
     * <desc>
     *      导出表单
     * </desc>
     *
     * @param operateAmountChangeGetPageDTO 运营-资金变动明细列表查询DTO
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/09/21
     */
    @ResponseBody
    @AuthAccessRequired
    @PostMapping("export")
    public Object export(OperateAmountChangeGetPageDTO operateAmountChangeGetPageDTO){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            operateAmountChangeGetPageDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateAmountChangeGetPageDTO.class,request);
            if (operateAmountChangeGetPageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!NumberHandlerUtil.isInRange(operateAmountChangeGetPageDTO.getAmountType(), 1, 3)
                    || StringUtils.isBlank(operateAmountChangeGetPageDTO.getTime())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<OperateAmountChangeGetPageVO> operateAmountChangeGetPageVOList = iOperateAmountChangeClient.getAllAmountChangeList(operateAmountChangeGetPageDTO);
            if (operateAmountChangeGetPageVOList == null || operateAmountChangeGetPageVOList.isEmpty()) {
                return new MessageVO(OperateErrorCodeEnum.EXPORT_DATA_EMPTY_ERR.getErrorCode());
            }
            String[] title;
            switch (operateAmountChangeGetPageDTO.getAmountType()){
                case 1:
                    title = new String[]{"序号","项目编号","项目名称","物业名称","交易前余额","交易金额","实时账户余额","手续费","创建时间","业务名称","业务编号","备注"};
                    break;
                case 2:
                    title = new String[]{"序号","第三方支付","交易前余额","交易金额","实时账户余额","手续费","创建时间","业务名称","业务编号","备注"};
                    break;
                case 3:
                    title = new String[]{"序号","第三方支付","交易前余额","交易金额","实时账户余额","手续费","创建时间","业务名称","业务编号","备注"};
                    break;
                default:
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            short rowHeight= 420;
            //创建excel工作簿
            HSSFWorkbook workbook=new HSSFWorkbook();
            //创建工作表sheet并设置简单格式
            HSSFSheet sheet=workbook.createSheet();
            sheet.setDefaultColumnWidth(15);
            //创建第一行
            HSSFRow row=sheet.createRow(0);
            row.setHeight(rowHeight);
            HSSFCell cell=null;
            //插入第一行数据的表头
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            //写入数据
            for (int amountChangeIndex = 0; amountChangeIndex < operateAmountChangeGetPageVOList.size(); amountChangeIndex++) {
                OperateAmountChangeGetPageVO operateAmountChangeGetPageVO = operateAmountChangeGetPageVOList.get(amountChangeIndex);
                int rowIndex = amountChangeIndex + 1; // 第一行已为标题行
                HSSFRow dataRow = sheet.createRow(rowIndex);
                dataRow.setHeight(rowHeight);
                HSSFCell noteCell = dataRow.createCell(0);
                noteCell.setCellValue(rowIndex);
                if (operateAmountChangeGetPageDTO.getAmountType() == 1) {
                    noteCell = dataRow.createCell(1);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getProjectId());
                    noteCell = dataRow.createCell(2);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getProjectName());
                    noteCell = dataRow.createCell(3);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getPropertyName());
                    noteCell = dataRow.createCell(4);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeBeforeAmount());
                    noteCell = dataRow.createCell(5);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeAmount());
                    noteCell = dataRow.createCell(6);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeAfterAmount());
                    noteCell = dataRow.createCell(7);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getHandlingFee());
                    noteCell = dataRow.createCell(8);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getCreateTime());
                    noteCell = dataRow.createCell(9);
                    switch (operateAmountChangeGetPageVO.getTradeType()){
                        case 1:
                            noteCell.setCellValue("物业、抄表费");
                            break;
                        case 2:
                            noteCell.setCellValue("维修费");
                            break;
                        case 3:
                            noteCell.setCellValue("停车费");
                            break;
                        case 8:
                            noteCell.setCellValue("物业提现");
                            break;
                        case 9:
                            noteCell.setCellValue("物业增值");
                            break;
                        default:
                            noteCell.setCellValue("");
                            break;
                    }
                    noteCell = dataRow.createCell(10);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getOutOrderNum());
                    noteCell = dataRow.createCell(11);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getRemark());
                } else {
                    if (operateAmountChangeGetPageDTO.getAmountType() == 2) {
                        noteCell = dataRow.createCell(1);
                        noteCell.setCellValue("微信支付");
                    }
                    if (operateAmountChangeGetPageDTO.getAmountType() == 3) {
                        noteCell = dataRow.createCell(1);
                        noteCell.setCellValue("银联支付");
                    }
                    noteCell = dataRow.createCell(2);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeBeforeAmount());
                    noteCell = dataRow.createCell(3);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeAmount());
                    noteCell = dataRow.createCell(4);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getTradeAfterAmount());
                    noteCell = dataRow.createCell(5);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getHandlingFee());
                    noteCell = dataRow.createCell(6);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getCreateTime());
                    noteCell = dataRow.createCell(7);
                    switch (operateAmountChangeGetPageVO.getTradeType()){
                        case 4:
                            noteCell.setCellValue("微信商户");
                            break;
                        case 5:
                            noteCell.setCellValue("微信提现");
                            break;
                        case 6:
                            noteCell.setCellValue("备付金充值");
                            break;
                        case 7:
                            noteCell.setCellValue("银联转账");
                            break;
                        default:
                            noteCell.setCellValue("");
                            break;
                    }
                    noteCell = dataRow.createCell(8);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getOutOrderNum());
                    noteCell = dataRow.createCell(9);
                    noteCell.setCellValue(operateAmountChangeGetPageVO.getRemark());
                }
            }
            String fileName = String.format("%s_FinanceManage_%s.xls",operateAmountChangeGetPageDTO.getToken(),DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"));
            fileName = URLEncoder.encode(fileName, "UTF-8");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            byte[] content = os.toByteArray();
            InputStream exportFileStream = new ByteArrayInputStream(content);
            String exportFileUrl = uploadFile(exportFileStream,fileName);
            if (StringUtils.isBlank(exportFileUrl)){
                return new MessageVO(OperateErrorCodeEnum.EXPORT_FILE_SAVE_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), (Object) exportFileUrl);
        } catch (Exception e) {
            throw new DataAccessException("【运营-资金变动明细】导出资金变动明细Excel失败",e);
        }
    }

    /**
     * <desc>
     *      Ftp上传文件，返回Url.
     * </desc>
     *
     * @param inputStream 文件流
     * @param fileName 文件名称
     * @return 文件上传成功后会返回Url,否则返回空
     * @author wangzhi
     * @createDate 2018/09/21
     */
    private String uploadFile(InputStream inputStream, String fileName) throws IOException {
        String fileUrl = "";
        String fileType = StringHandlerUtil.copySubStr(fileName, fileName.lastIndexOf('.') + 1, fileName.length());
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                inputStream,
                fileType,
                FILE_ACCESS_URL,
                FileCatalogEnum.EXPORT_EXCEL_ZHANG_FILE.getType()
        );
        Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
        Boolean returnCode = (Boolean)resultMap.get("returnCode");
        if (returnCode == false){
            return fileUrl;
        }
        fileUrl = resultMap.get("accessPath").toString();
        return fileUrl;
    }

}
